<template>
  <div class="create-application">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1 class="page-title">创建应用</h1>
      <p class="page-description">基于选择的API服务创建您的智能应用</p>
    </div>

    <!-- 应用创建表单 -->
    <div class="create-form">
      <div class="form-container">
        <!-- 选择的服务信息 -->
        <div class="service-selection">
          <h3>选择服务</h3>
          <div v-if="!selectedService" class="service-selector">
            <div class="form-group">
              <label for="serviceSelect">API服务 <span class="required">*</span></label>
              <select id="serviceSelect" v-model="selectedServiceId" @change="handleServiceSelect" required>
                <option value="">请选择API服务</option>
                <option v-for="service in apiServices" :key="service.apiId" :value="service.apiId">
                  {{ service.apiName }}
                </option>
              </select>
            </div>
          </div>
          <div v-if="selectedService" class="selected-service">
            <div class="service-card">
              <div class="service-info">
                <h4>{{ selectedService.apiName }}</h4>
                <p>{{ selectedService.apiDescription }}</p>
                <span class="service-type">{{ getServiceTypeName(selectedService.apiType) }}</span>
              </div>
              <button type="button" class="btn-change-service" @click="changeService">更换服务</button>
            </div>
          </div>
        </div>

        <!-- 应用配置表单 -->
        <div class="app-config">
          <h3>应用配置</h3>
          <form @submit.prevent="createApp">
            <div class="form-group">
              <label for="appName">应用名称 <span class="required">*</span></label>
              <input 
                type="text" 
                id="appName" 
                v-model="appForm.appName" 
                placeholder="请输入应用名称"
                maxlength="100"
                required
              />
            </div>

            <div class="form-group">
              <label for="appDescription">应用描述</label>
              <textarea 
                id="appDescription" 
                v-model="appForm.appDescription" 
                placeholder="请输入应用描述"
                rows="4"
                maxlength="1000"
              ></textarea>
            </div>

            <div class="form-group">
              <label for="appType">应用类型 <span class="required">*</span></label>
              <select id="appType" v-model="appForm.appType" required>
                <option value="">请选择应用类型</option>
                <option value="手动">手动执行</option>
                <option value="定时">定时执行</option>
                <option value="全部">全部模式</option>
              </select>
            </div>

            <!-- 定时任务配置 -->
            <div v-if="appForm.appType === '定时' || appForm.appType === '全部'" class="timing-config">
              <h4>定时任务配置</h4>
              <div class="form-row">
                <div class="form-group half">
                  <label for="startTime">开始时间</label>
                  <input 
                    type="datetime-local" 
                    id="startTime" 
                    v-model="appForm.startTime"
                  />
                </div>
                <div class="form-group half">
                  <label for="endTime">结束时间</label>
                  <input 
                    type="datetime-local" 
                    id="endTime" 
                    v-model="appForm.endTime"
                  />
                </div>
              </div>
              
              <div class="form-group">
                <label for="cronExpression">Cron表达式 <span class="required">*</span></label>
                <div class="cron-input-group">
                  <input 
                    type="text" 
                    id="cronExpression" 
                    v-model="taskConfig.cronExpression"
                    placeholder="请输入Cron表达式，如：0 0 9 * * ?（每天9点执行）"
                    readonly
                    required
                  />
                  <button type="button" class="btn-generate-cron" @click="showCronDialog">
                    生成表达式
                  </button>
                </div>
                <small class="cron-help">格式：秒 分 时 日 月 周 年（可选）</small>
              </div>
              
              <div class="form-group">
                <label for="taskRemark">定时任务备注</label>
                <textarea 
                  id="taskRemark" 
                  v-model="taskConfig.remark" 
                  placeholder="请输入定时任务备注信息"
                  rows="2"
                  maxlength="200"
                ></textarea>
              </div>
            </div>

            <div class="form-group">
              <label for="deviceId">关联设备</label>
              <select id="deviceId" v-model="appForm.deviceId">
                <option value="">请选择设备（可选）</option>
                <option v-for="device in devices" :key="device.deviceId" :value="device.deviceId">
                  {{ device.deviceName }}
                </option>
              </select>
            </div>

            <div class="form-group">
              <label for="remark">备注</label>
              <textarea 
                id="remark" 
                v-model="appForm.remark" 
                placeholder="请输入备注信息"
                rows="3"
                maxlength="500"
              ></textarea>
            </div>

            <div class="form-actions">
              <button type="button" class="btn-cancel" @click="goBack">取消</button>
              <button type="submit" class="btn-create" :disabled="loading">{{ loading ? '创建中...' : '创建应用' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Cron表达式生成器对话框 -->
    <el-dialog title="Cron表达式生成器" v-model="openCron" append-to-body destroy-on-close class="scrollbar" width="800px">
     <Crontab ref="crontabRef" @hide="openCron=false" @fill="crontabFill" :expression="expression"></Crontab>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import appAPI from '@/api/agriculture/xctl/appManage'
import { apiServiceAPI } from '@/api/agriculture/xctl/apiService'
import Crontab from '@/components/agriculture/xctl/Crontab/index.vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const selectedService = ref(null)
const selectedServiceId = ref('')
const apiServices = ref([])
const categories = ref([])
const devices = ref([])

// 应用表单数据
const appForm = ref({
  appName: '',
  appDescription: '',
  appType: '',
  startTime: '',
  endTime: '',
  deviceId: '',
  remark: '',
  apiId: null
})

// 定时任务配置
const taskConfig = ref({
  cronExpression: '',
  remark: ''
})

// Cron表达式生成器相关
const openCron = ref(false)
const expression = ref('')

// 获取分类数据
const fetchCategories = async () => {
  try {
    const token = getToken()
    const baseURL = import.meta.env.VITE_APP_BASE_API || '/dev-api'
    const response = await fetch(`${baseURL}/customer/api/type/list`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await response.json()
    if (data.code === 200) {
      categories.value = data.rows
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}

// 获取设备列表
const fetchDevices = async () => {
  try {
    const token = getToken()
    const baseURL = import.meta.env.VITE_APP_BASE_API || '/dev-api'
    const response = await fetch(`${baseURL}/customer/device/list`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await response.json()
    if (data.code === 200) {
      devices.value = data.rows || []
    }
  } catch (error) {
    console.error('获取设备列表出错:', error)
    // 模拟设备数据
    devices.value = [
      { deviceId: 1, deviceName: '象差检测设备-01' },
      { deviceId: 2, deviceName: '象差检测设备-02' },
      { deviceId: 3, deviceName: '象差分析设备-01' }
    ]
  }
}

// 获取服务类型名称
const getServiceTypeName = (apiType) => {
  const category = categories.value.find(cat => cat.dictValue === apiType)
  return category ? category.dictLabel : '其他服务'
}

// 显示Cron表达式生成器
const showCronDialog = () => {
  expression.value = taskConfig.value.cronExpression
  openCron.value = true
}

// Cron表达式生成器回调
const crontabFill = (value) => {
  taskConfig.value.cronExpression = value
  ElMessage.success('Cron表达式已生成')
}

// 创建应用
const createApp = async () => {
  try {
    loading.value = true
    
    // 验证必填字段
    if (!appForm.value.appName.trim()) {
      alert('请输入应用名称')
      return
    }
    
    if (!appForm.value.appType) {
      alert('请选择应用类型')
      return
    }
    
    // 验证定时任务时间
    if ((appForm.value.appType === '定时' || appForm.value.appType === '全部') && appForm.value.startTime && appForm.value.endTime) {
      if (new Date(appForm.value.startTime) >= new Date(appForm.value.endTime)) {
        alert('结束时间必须大于开始时间')
        return
      }
    }
    
    // 验证定时任务配置
    if ((appForm.value.appType === '定时' || appForm.value.appType === '全部')) {
      if (!taskConfig.value.cronExpression.trim()) {
        alert('定时任务需要配置Cron表达式')
        return
      }
    }
    
    const appData = {
      appName: appForm.value.appName.trim(),
      apiId: selectedService.value?.apiId,
      appDescription: appForm.value.appDescription?.trim() || null,
      appType: appForm.value.appType,
      startTime: appForm.value.startTime || null,
      endTime: appForm.value.endTime || null,
      deviceId: appForm.value.deviceId || null,
      remark: appForm.value.remark?.trim() || null,
      status: '0', // 默认正常状态
      delFlag: '0' // 默认未删除
    }
    
    // 构建请求数据（包含定时任务配置）
    const requestData = {
      appManage: appData,
      taskConfig: null
    }
    
    // 如果是定时或全部类型，添加定时任务配置
    if ((appForm.value.appType === '定时' || appForm.value.appType === '全部') && taskConfig.value.cronExpression.trim()) {
      requestData.taskConfig = {
        cronExpression: taskConfig.value.cronExpression.trim(),
        remark: taskConfig.value.remark?.trim() || '应用定时任务'
      }
    }
    
    // 调用创建应用的API
    console.log('创建应用数据:', requestData)
    
    const result = await appAPI.createApp(requestData)
    
    if (result.code === 200 || result.success) {
      alert('象差推理应用创建成功！')
      router.push('/agriculture/applications')
    } else {
      throw new Error(result.message || '应用创建失败')
    }
    
  } catch (error) {
    console.error('创建应用失败:', error)
    alert('创建应用失败，请重试')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取API服务列表
const fetchApiServices = async () => {
  try {
    loading.value = true
    const response = await apiServiceAPI.getApiServiceList()
    if (response.code === 200) {
      apiServices.value = response.rows || []
    } else {
      console.error('获取API服务列表失败:', response.msg)
    }
  } catch (error) {
    console.error('获取API服务列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 处理服务选择
const handleServiceSelect = () => {
  if (!selectedServiceId.value) {
    selectedService.value = null
    appForm.value.apiId = null
    return
  }
  
  const service = apiServices.value.find(s => s.apiId === selectedServiceId.value)
  if (service) {
    selectedService.value = service
    appForm.value.apiId = service.apiId
  }
}

// 更换服务
const changeService = () => {
  selectedService.value = null
  selectedServiceId.value = ''
  appForm.value.apiId = null
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchDevices()
  fetchApiServices()
  
  // 从路由参数获取选择的服务信息
  if (route.query.service) {
    try {
      selectedService.value = JSON.parse(decodeURIComponent(route.query.service))
      appForm.value.apiId = selectedService.value.apiId
      selectedServiceId.value = selectedService.value.apiId
    } catch (error) {
      console.error('解析服务信息失败:', error)
    }
  }
})
</script>

<style scoped>
.create-application {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 48px;
  
}

.page-title {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin-bottom: 16px;
}

.page-description {
  font-size: 18px;
  color: #6b7280;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

.create-form {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-container {
  padding: 32px;
}

.service-selection {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e5e7eb;
}

.service-selection h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.service-selector {
  margin-bottom: 15px;
}

.service-selector .form-group {
  margin-bottom: 15px;
}

.selected-service {
  margin-top: 20px;
}

.service-card {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.service-info {
  flex: 1;
}

.service-info h4 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.service-info p {
  color: #6b7280;
  margin-bottom: 12px;
  line-height: 1.5;
}

.service-type {
  display: inline-block;
  background: #3b82f6;
  color: white;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.btn-change-service {
  padding: 8px 16px;
  background-color: #f3f4f6;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  color: #374151;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
  transition: all 0.2s;
}

.btn-change-service:hover {
  background-color: #e5e7eb;
}

.app-config h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group.half {
  flex: 1;
  margin-right: 16px;
}

.form-group.half:last-child {
  margin-right: 0;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
  font-size: 14px;
}

.required {
  color: #ef4444;
  margin-left: 4px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.timing-config {
  background: #f8fafc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  border: 1px solid #e2e8f0;
}

.timing-config h4 {
   margin: 0 0 16px 0;
   color: #1f2937;
   font-size: 16px;
   font-weight: 600;
 }

 .cron-input-group {
   display: flex;
   gap: 12px;
   align-items: center;
 }
 
 .cron-input-group input {
   flex: 1;
 }
 
 .btn-generate-cron {
   padding: 8px 16px;
   background: #10b981;
   color: white;
   border: none;
   border-radius: 6px;
   font-size: 12px;
   font-weight: 500;
   cursor: pointer;
   transition: all 0.2s ease;
   white-space: nowrap;
 }
 
 .btn-generate-cron:hover {
   background: #059669;
 }
 
 .cron-help {
   display: block;
   margin-top: 6px;
   color: #6b7280;
   font-size: 12px;
   line-height: 1.4;
 }

 .form-group input[type="text"],
 .form-group input[type="datetime-local"],
 .form-group textarea,
 .form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.form-group input[type="text"]:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 100px;
}

.form-group input[type="checkbox"] {
  margin-right: 8px;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.btn-cancel {
  padding: 12px 24px;
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-cancel:hover {
  background: #e5e7eb;
}

.btn-create {
  padding: 12px 24px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-create:hover:not(:disabled) {
  background: #2563eb;
}

.btn-create:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .create-application {
    padding: 20px 12px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn-cancel,
  .btn-create {
    width: 100%;
  }
}

/* Cron表达式生成器样式 */
.scrollbar {
  max-height: 80vh;
  overflow-y: auto;
}

.scrollbar::-webkit-scrollbar {
  width: 6px;
}

.scrollbar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.scrollbar::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.scrollbar::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>